const nodemailer = require('nodemailer')
const schedule = require('node-schedule')
const fs = require('fs')
const log4js = require('log4js');

const logger = log4js.getLogger();
console.log('邮件')

//日志
log4js.configure({
  appenders: {
    cheeseLogs: { type: 'file', filename: 'cheese.log' },
    console: { type: 'console' }
  },
  categories: {
    cheese: { appenders: ['cheeseLogs'], level: 'error' },
    another: { appenders: ['console'], level: 'trace' },
    default: { appenders: ['console', 'cheeseLogs'], level: 'trace' }
  }
});

var subject = '';
dateObj = new dateObj()
schedule.scheduleJob('0 0 9 * * *',function(){ //发日报：每天早晨9:00
  console.log('发日报')
  var currentTime = dateObj.getCurrentTime()
  subject = currentTime.y + '-' + currentTime.m + '-' + currentTime.d+'运营日报'
  toSendEmail(subject,'day')
});
schedule.scheduleJob('0 0 9 * * 5',function(){ //发周报：每周五早晨9:00
  console.log('发周报')
  var currentTime = dateObj.getCurrentTime()
  subject = dateObj.getLastWeekTime().dateStr+'至'+currentTime.y + '-' + currentTime.m + '-' + currentTime.d+'运营周报'
  toSendEmail(subject,'week')
});
schedule.scheduleJob('0 0 9 1 * *',function(){ //发月报：每月1号早晨9:00
  console.log('发月报')
  subject = dateObj.getLastMonthTime().year + '年'+ dateObj.getLastMonthTime().month +'运营月报'
  toSendEmail(subject,'month')
});
schedule.scheduleJob('0 0 9 1 7 *',function(){ //发上半年报：7月1日早晨9:00
  console.log('发上半年报')
  var currentTime = dateObj.getCurrentTime()
  subject = currentTime.y+'年1月-'+currentTime.y+'年6月'+'运营上半年报'
  toSendEmail(subject,'firstHalf')
});
schedule.scheduleJob('0 0 9 1 1 *',function(){ //发下半年报：每年1月1日早晨9:00
  console.log('发下半年报')
  var currentTime = dateObj.getCurrentTime()
  subject = (currentTime.y-1)+'年7月'+(currentTime.y-1)+'年12月'+'运营下半年报'
  toSendEmail(subject,'secondHalf')
});
// schedule.scheduleJob('0 1 9 1 1 *',function(){ //年报：每年1月1日早晨9:01
//   subject = (currentTime.y-1) + '运营年报'
//   toSendEmail(subject,'year')
// });


function toSendEmail(subject,fileName) {
  var transporter = nodemailer.createTransport({
    host:"smtp.exmail.qq.com", //smtp.exmail.qq.com  //smtp.qq.com
    secure:true,
    port:465,
    auth: {
      user: "sunyan@medatc.com", //sunyan@medatc.com ,3241678631@qq.com
      pass: "xuanJING0808"
    },
    debug: true
  })
  var message = {
    from:"sunyan@medatc.com",  //reporter
    to:"wangyifan@medatc.com, sunyan@medatc.com", //receiver list：3241678631@qq.com, sunyan@medatc.com, wangyifan@medatc.com
    subject:subject,
    html:'<p>关键数据图表：</p><img src="cid:key"/>，<p>趋势统计图表：</p><img src="cid:trend"/>',

    attachments:[
      {
        filename: 'key',
        path: __dirname + '/chart_images/chart_report_key_'+fileName+'.png',
        cid: 'key'
      },
      {
        filename: 'trend',
        path: __dirname + '/chart_images/chart_report_trend_'+fileName+'.png',
        cid: 'trend'
      }
    ]
  }
  transporter.sendMail(message, (error, info) => {
    if (error) {
      console.log(error.message);
      return;
    }
    console.log('Server responded with "%s"', info.response);
    logger.debug({
      from:'sunyan <sunyan@medatc.com>',
      to:'王怡凡 <wangyifan@medatc.com>',
      time: new Date()
    });
    transporter.close();
  });
}

/*
 * @getLastWeekTime 获取一周以前的日期
 * @getLastMonthTime 获取上个月的日期
 * */
function dateObj(){
  this.getLastWeekTime = function (){
    var today = new Date();
    var current=today.getTime();
    var minusDate=1000*60*60*24*7;
    var time = new Date(current-minusDate);
    var yearW = time.getFullYear(),
      monthW = time.getMonth()+1,
      dayW = time.getDate()
    var dateStr = yearW +'-'+ (monthW>=10?monthW:'0'+monthW)+'-'+dayW
    var obj = {
      year: yearW,
      month:monthW,
      day:dayW,
      dateStr:dateStr
    }
    return obj
  }
  this.getLastMonthTime = function () {  //获取上个月第一天和最后一天
    var today = new Date();
    var yearM = today.getFullYear();
    var monthM = today.getMonth();
    if (monthM==0) {
      monthM=12;
      yearM=yearM-1;
    }
    if (monthM < 10) {
      monthM = "0" + monthM;
    }
    var firstDay = yearM + "-" + monthM + "-" + "01"; //上个月的第一天
    var lastDay = year + "-" + (month>=10?month:'0'+month) + "-" + '01'; //本月一天
    var obj = {
      year:yearM,
      month:monthM,
      firstDay:firstDay,
      lastDay:lastDay,
    }
    return obj
  }
  this.getCurrentTime = function () {
    var today = new Date();
    var obj = {
      y: today.getFullYear(),  //年
      m: today.getMonth() + 1, //月
      d: today.getDate() //日
    }
    return obj
  }
}

